package com.hbsx.utils;

import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.lang.StringUtils;

import javax.naming.NoPermissionException;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

public class JwtUtil {

    public static String generateToken(String user){
        HashMap<String,Object> map = new HashMap<>();
        map.put("id",new Random().nextInt());
        map.put("user",user);
        String jwt = Jwts.builder()
                .setSubject("user info")
                .setClaims(map)
                .signWith(SignatureAlgorithm.HS512,"hopshine")
                .compact();
//        String finalJwt = "rry-"+jwt;
        return jwt;
    }

    public static Map<String,Object> validateToken(String token) throws Exception {
        if (token!=null){
            HashMap<String,Object> map = new HashMap<>();
            Map<String,Object> body = Jwts.parser().setSigningKey("hopshine").parseClaimsJws(token).getBody();
            String id = (String) body.get("id");
            String user = (String) body.get("user");
            if (StringUtils.isEmpty(user)){
                throw new Exception();
            }
            map.put("id",body.get("id"));
            map.put("user",body.get("user"));
            return map;
        }else {
            throw new Exception();
        }
    }
}
